package cn.haut.online_read.controller;

import cn.haut.online_read.enrity.User;
import cn.haut.online_read.mapper.UserMapper;
import cn.haut.online_read.service.UserService;
import cn.haut.online_read.utils.Constant;
import cn.haut.online_read.utils.RedisUtils;
import cn.haut.online_read.utils.TokenUtils;
import cn.haut.online_read.utils.toMapList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

import static cn.haut.online_read.utils.Constant.PERMIS_ADMIN;
import static cn.haut.online_read.utils.Constant.TOKEN_KEY;
import static cn.haut.online_read.utils.ResponseUtils.*;

/**
 * @author xing
 * @date 2021-05-20 16:16
 */
@Controller(value = "adminController")
@RequestMapping(value = "/admin")
public class AdminController {

    private TokenUtils tokenUtils;
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setTokenUtils(TokenUtils tokenUtils) {
        this.tokenUtils = tokenUtils;
    }

    /**
     * 获取所有用户信息
     *
     * @param requestMap
     * @param token
     * @return
     */
    @PostMapping("/getAllUsers")
    @ResponseBody
    public String getAllUsers(
            @RequestBody Map<String, String> requestMap,
            @RequestHeader(TOKEN_KEY) String token
    ) {
        // 获取参数
        String username = requestMap.get("username");
        int pageSize = Integer.parseInt(requestMap.get("pageSize"));
        int currentPage = Integer.parseInt(requestMap.get("currentPage"));

        // token 验证
        if (token == null || !tokenUtils.validateToken(username, token)) {
            // return
            return createTokenError();
        }
        int permission = userService.getPermissionByName(username);
        if (permission == Constant.PERMIS_ADMIN) {
            // 获取所有普通用户，由于权限一定，密码不获取，所以这里只获取了用户名
//            List<String> userNamesList = userService.getAllUsers();
            List<String> userNamesList = userService.getUsersByPagination(pageSize, currentPage);
            int count = userService.getAllUsersCount();

            // 返回 结果
            Map<String, Object> responseMap = new HashMap<>();
            List<Map<String, Object>> users = toMapList.get(
                    Arrays.asList("name"),
                    userNamesList
            );
            responseMap.put("users", users);
            responseMap.put("count", count);
            return addSuccess(responseMap);
        } else {
            return createTokenError();
        }
    }

    /**
     * 删除用户
     *
     * @param requestMap
     * @param token
     * @return
     */
    @PostMapping(value = "/deleteUser")
    @ResponseBody
    public String deleteUser(
            @RequestBody Map<String, String> requestMap,
            @RequestHeader(TOKEN_KEY) String token
    ) {
        String username = requestMap.get("username");
        String deleteUsername = requestMap.get("deleteUsername");

        // token 验证
        if (token == null || !tokenUtils.validateToken(username, token)) {
            // return
            return createTokenError();
        }

        // 权限不足
        if (deleteUsername != null && userService.getPermissionByName(username) != PERMIS_ADMIN) {
            return createError("你没有该没有权限");
        }

        // 设置 删除 哪一个用户，deleteUsername 为空，证明为用户自己 选择 注销 自己的账户
        String deleteUserUsername = deleteUsername == null ? username : deleteUsername;

        // 删除用户
        boolean delete = userService.deleteUser(deleteUserUsername);
        // 删除成功
        if (delete) {
            return createSuccess();
        } else {
            return createError("删除失败");
        }
    }

    @PostMapping(value = "/searchUser")
    @ResponseBody
    public String serachUserByUsername(
            @RequestBody Map<String, String> requestMap,
            @RequestHeader(TOKEN_KEY) String token
    ) {
        String username = requestMap.get("username");
        String searchUsername = requestMap.get("searchUsername");
        int pageSize = Integer.parseInt(requestMap.get("pageSize"));
        int currentPage = Integer.parseInt(requestMap.get("currentPage"));

        // token 验证
        if (token == null || !tokenUtils.validateToken(username, token)) {
            // return
            return createTokenError();
        }

        // 权限不足
        if (userService.getPermissionByName(username) != PERMIS_ADMIN) {
            return createError("你没有该没有权限");
        }

        // 获取 查找结果
        List<String> userNameList = userService.searchUserByPagination(searchUsername, pageSize, currentPage);
        int count = userService.getAllUsersCountByUsername(searchUsername);

        // 返回结果,
        Map<String, Object> responseMap = new HashMap<>();
        // 转为 Map 的 list 是为了 前端使用 el-table 时显示 每一项的 name
        List<Map<String, Object>> nameMapList = toMapList.get(
                Collections.singletonList("name"),
                userNameList
        );
        responseMap.put("users", nameMapList);
        responseMap.put("count", count);
        return addSuccess(responseMap);
    }
}
